#include "ObStarEdible.h"
#include "D3DApp.h"
#include "Collision.h"
#include "ObPlayer.h"
#include "ObDeathField.h"

ObStarEdible::ObStarEdible(IDirect3DTexture9* mtex, float px, float py){
	mID		= 0;
	mInfo	= 0;
	mWidth	= 16.0f;
	mHeight	= 16.0f;
	mCenter = D3DXVECTOR3(mWidth/2, mHeight/2, 0.0f);
	mSpritePos.x = 8;
	mSpritePos.y = 8;

	mNeedCollision = false;
	mTex = mtex;
	mPos.x = px;
	mPos.y = py;
	
	mIsXGravity = false;
	mIsYGravity = false;

	mVelocity.x = 0.0f;
	mVelocity.y = 30.0f;
	
	MAX_VELOCITYX = 400;
	MAX_VELOCITYY = 300;

	count = 0.0f;
	topCount = py;
	flyCount = 0.0f;
	mCurrentSprite = 0;
	canMove = false;
}

ObStarEdible::~ObStarEdible(){
	
}

void ObStarEdible::collidedWith(ObObject* object, CollisionRS rs){
	switch (object->getId())
	{
	case ObPlayer::MARIO:
		if(ObPlayer* player  = dynamic_cast<ObPlayer*>(object)){
			mNeedCollision = false;
			mNeedDispose = true;
		}
		break;
	case ObDeathField::Deathfield1:
		mNeedDispose = true;
		break;
	default:
		if(rs.mState == Left){
			mVelocity.x = -mVelocity.x;
		}
		if(rs.mState == Right){
			mVelocity.x = -mVelocity.x;
		}
		if(rs.mState == Bottom){
			mVelocity.y = 0.0f;
			mIsJump = false;
		}
		break;
	}
}
void ObStarEdible::update(float dt){
	if(mNeedDispose) return;

	if(mIsJump){
		flyCount+=dt;
		if(flyCount>=5.0f){
			mNeedDispose = true;
			flyCount = 0.0f;
		}
	}else{
		flyCount= 0.0f;
	}

	count+=dt;
	if(count>=0.1f){
		mCurrentSprite++;
		if(mCurrentSprite >=3){
			mCurrentSprite = 0;
		}
		count = 0.0f;
	}

	mSpritePos.x = 8 + mCurrentSprite*16.0f;
	mSpritePos.y = 8.0f;

	if(canMove){
		if(mIsJump == false){
			mVelocity.y = 400.0f;
		}
	}

	if(topCount == -std::numeric_limits<float>::infinity()){
		return;
	}


	if((mPos.y - topCount) >= 16.0f){
		mVelocity.x = 100.0f;
		mVelocity.y = 0.0f;
		mNeedCollision = true;
		mIsYGravity = true;
		topCount = -std::numeric_limits<float>::infinity();
		canMove = true;
	}
}
void ObStarEdible::render(ID3DXSprite* mSprite){
	if(mNeedDispose) return;

	HR(gDevice->SetRenderState(D3DRS_ALPHATESTENABLE,true));
	D3DXMATRIX S;
	D3DXMatrixScaling(&S,1.0f,-1.0f,1.0f);
	D3DXMATRIX R;
	D3DXMatrixRotationZ(&R, mRotation);
	D3DXMATRIX T;
	D3DXMatrixTranslation(&T,mPos.x - gCamera->getPos().x, mPos.y - gCamera->getPos().y, 0);
	mSprite->SetTransform(&(S*R*T));

	RECT rect = calRenderRECT(mSpritePos,mWidth,mHeight);
	mSprite->Draw(mTex,&rect,&mCenter,0,D3DCOLOR_XRGB(255, 255, 255));
	mSprite->Flush();
	HR(gDevice->SetRenderState(D3DRS_ALPHATESTENABLE,false));
}
void ObStarEdible::clear(){
	mTex = NULL;
}

